package org.demo.base.file.mapper.impl;

import org.demo.base.file.domain.SysFile;
import org.demo.base.file.mapper.FileMapper;
import org.demo.base.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.Statement;
import java.time.LocalDateTime;

/**
 * @author tomdog
 */
@Repository
public class FileMapperImpl implements FileMapper {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public SysFile insert(SysFile u) {
        // 创建时间设置为现在
        u.setCreateTime(LocalDateTime.now());
        // 返回自增主键
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(
                connection -> {
                    PreparedStatement pstmt = connection.prepareStatement(
                            "insert into t_sys_file(type, path, file_name, orginal_file_name, category, create_time) " +
                                    "values (?, ?, ?, ?, ?, ?)"
                            , Statement.RETURN_GENERATED_KEYS
                    );
                    pstmt.setString(1, u.getType());
                    pstmt.setString(2, u.getPath());
                    pstmt.setString(3, u.getFileName());
                    pstmt.setString(4, u.getOirginalName());
                    pstmt.setString(5, u.getCategory());
                    pstmt.setDate(6, DateUtil.toSqlDate(u.getCreateTime()));
                    return pstmt;
                }
                , keyHolder
        );
        u.setId(keyHolder.getKey().longValue());
        return u;
    }
}
